package com.appleframework.module.usermgr.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件上传
 * @author Administrator
 *
 */
public class Fileupload {
	
	/**
	 * 文件上传
	 * @param request 请求参数
	 * @param response 响应参数
	 * @return 返回文件存储的路径--用于存入数据库
	 */
	public String fileUpload(HttpServletRequest request,HttpServletResponse response) {
		Calendar calendar=Calendar.getInstance();
		int year=calendar.get(Calendar.YEAR);
		int month=calendar.get(Calendar.MONTH);
		int date=calendar.get(Calendar.DATE);
		
		   //转型为MultipartHttpRequest
			  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
			 	  //根据前台的name名称得到上传的文件
			  MultipartFile file_path1 = multipartRequest.getFile("file_path1");  
			      // 获得文件名：   
			      String  realFileName = file_path1.getOriginalFilename();
			      String realFileName1=new SimpleDateFormat("yyyyMMddHHmmSS").format(new Date())+realFileName.substring(realFileName.lastIndexOf("."), realFileName.length());
			      System.out.println("转换后的文件名："+realFileName1);
			        //获取路径
			      String ctxPath = request.getContextPath();
			      ctxPath = request.getSession().getServletContext().getRealPath("/")+""+"\\images\\";
			      System.out.println("路径："+ctxPath);
			   // 创建文件
			      File dirPath = new File(ctxPath+year+"\\"+(month+1)+"\\"+date);
			      System.out.println("建立的文件夹路径："+dirPath);
			    
			      if(!dirPath.exists())
			      {
			       dirPath.mkdirs();
			      }
			      File uploadFile = new File(dirPath+"\\"+realFileName1);
			      System.out.println("文件存储路径："+dirPath+"\\"+realFileName1);
			      //
			      try {
					
					OutputStream oStream=new FileOutputStream(uploadFile);
					oStream.write(file_path1.getBytes());
					oStream.close();
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			      


		
		
		return dirPath+"\\"+realFileName1;
	}

}
